import sys
import json
import os
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
from PySide6.QtCore import QEvent
from ui_login import Ui_MainWindow
from soft_keyboard import SoftKeyboard

CACHE_PATH = os.path.join(os.path.dirname(__file__), 'cache', 'login.json')
FOCUSIN  = 10
FOCUSOUT = 11

ADMIN_MOD = False
def read_login_data():
	if not os.path.exists(CACHE_PATH):
		return {}
	try:
		with open(CACHE_PATH, 'r', encoding='utf-8') as f:
			data = f.read().strip()
			if not data:
				return {}
			return json.loads(data)
	except Exception:
		return {}

def write_login_data(username, password):
	data = {"username": username, "password": password}
	with open(CACHE_PATH, 'w', encoding='utf-8') as f:
		json.dump(data, f, ensure_ascii=False)

class LoginWindow(QMainWindow):
	def __init__(self):
		super().__init__()
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.pushButton.clicked.connect(self.login)
		self.ui.pushButton_2.clicked.connect(self.signup)

		self.soft_keyboard = SoftKeyboard()
		self.ui.plainTextEdit.installEventFilter(self)
		self.ui.plainTextEdit_2.installEventFilter(self)

	def eventFilter(self, obj, event):
		if obj in [self.ui.plainTextEdit, self.ui.plainTextEdit_2]:
			print(f"eventFilter: obj={obj}, type={event.type()}")
			if event.type() == FOCUSIN:
				pos = obj.mapToGlobal(obj.rect().bottomLeft())
				self.soft_keyboard.set_target(obj)
				self.soft_keyboard.show_at(pos)
				print("软键盘弹出，控件：", obj, "坐标：", pos)
			# elif event.type() == FOCUSOUT:
			# 	next_widget = QApplication.focusWidget()
			# 	print("下一个获得焦点的控件：", next_widget)
			# 	if next_widget not in [self.soft_keyboard]:
			# 		self.soft_keyboard.hide()
			# 	print("软键盘关闭")
		return super().eventFilter(obj, event)

	def login(self):
		username = self.ui.plainTextEdit.toPlainText().strip()
		password = self.ui.plainTextEdit_2.toPlainText().strip()
		data = read_login_data()
		if not data:
			QMessageBox.warning(self, "登录失败", "未注册用户，请先注册！")
			return
		if username == data.get("username") and password == data.get("password"):
			QMessageBox.information(self, "登录成功", f"欢迎，{username}！")
		else:
			QMessageBox.critical(self, "登录失败", "用户名或密码错误！")

	def signup(self):
		username = self.ui.plainTextEdit.toPlainText().strip()
		password = self.ui.plainTextEdit_2.toPlainText().strip()
		if not username or not password:
			QMessageBox.warning(self, "注册失败", "用户名和密码不能为空！")
			return
		if ADMIN_MOD:
			write_login_data(username, password)
			QMessageBox.information(self, "注册成功", "注册成功，请登录！")
		else:
			QMessageBox.warning(self, "注册失败", "当前不允许注册新用户，请联系管理员！")

if __name__ == "__main__":
	app = QApplication(sys.argv)
	window = LoginWindow()
	window.show()
	sys.exit(app.exec())
